<template>
  <div class="top-select-mobile">
    <van-nav-bar :title="showDeptName + '数据看板'" fixed placeholder @click-right="onClickRight">
      <i slot="right" class="el-icon-close" v-show="showCloseBtn" />
    </van-nav-bar>

    <div class="select-box">
      <el-row>
        <el-col :span="8">
          <div class="label-box" @click="openDeptPicker">
            <span class="label">{{ showDeptName }}</span>
            <i class="el-icon-arrow-down" />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="label-box" @click="processPicker = true">
            <span class="label">{{ showProcessName }}</span>
            <i class="el-icon-arrow-down" />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="label-box" @click="rdcPicker = true">
            <span class="label">{{ showrRdcName }}</span>
            <i class="el-icon-arrow-down" />
          </div>
        </el-col>
      </el-row>
      <div class="label-box" style="margin-top: 15px">
        <div class="label-box" @click="openMonthPicker('from')">
          <span class="label">{{ showMonthFrom }}</span>
          <i class="el-icon-arrow-down" />
        </div>
        <div style="margin: 0 10px">-</div>
        <div class="label-box" @click="openMonthPicker('to')">
          <span class="label">{{ showMonthTo }}</span>
          <i class="el-icon-arrow-down" />
        </div>
      </div>
    </div>

    <van-popup v-model="deptPicker" round position="bottom" :style="{ minHeight: '30%' }">
      <van-cascader v-model="pickDeptId" :options="deptTree" :field-names="{ text: 'label' }" placeholder="全部" :closeable="false" @finish="onDeptFinish">
        <div slot="title" class="dept-tree-title">
          <button class="van-picker__cancel" style="padding-left: 0" @click="deptPicker = false">取消</button>
          选择检查部门
          <div>
            <!-- <button class="van-picker__confirm" @click="changeDeptId('')">全集团</button> -->
            <button class="van-picker__confirm" style="padding-right: 0" @click="onDeptConfirm">确认</button>
          </div>
        </div>
      </van-cascader>
    </van-popup>

    <van-popup v-model="processPicker" round position="bottom" :style="{ minHeight: '30%' }">
      <van-picker title="选择过程分类" show-toolbar :columns="processTypeList" value-key="label" @cancel="processPicker = false" @confirm="onProcessPicker" />
    </van-popup>
    <van-popup v-model="rdcPicker" round position="bottom" :style="{ minHeight: '30%' }">
      <van-picker title="选择检查类型" show-toolbar :columns="rdcTypeList" value-key="label" @cancel="rdcPicker = false" @confirm="onRdcPicker" />
    </van-popup>
    <van-popup v-model="monthFromPicker" round position="bottom" :style="{ minHeight: '30%' }">
      <van-datetime-picker title="选择起始月份" v-model="currMonthFrom" type="year-month" :max-date="maxDate" :formatter="monthFmt" @cancel="monthFromPicker = false" @confirm="onMonthFromPicker" />
    </van-popup>
    <van-popup v-model="monthToPicker" round position="bottom" :style="{ minHeight: '30%' }">
      <van-datetime-picker title="选择结束月份" v-model="currMonthTo" type="year-month" :max-date="maxDate" :formatter="monthFmt" @cancel="monthToPicker = false" @confirm="onMonthToPicker" />
    </van-popup>
  </div>
</template>
<script>
// 顶部选择框，用于移动端
// 按需导入 vantUI 组件
import VanNavBar from 'vant/lib/nav-bar'
import 'vant/lib/nav-bar/style'
import VanPopup from 'vant/lib/popup'
import 'vant/lib/popup/style'
import VanCascader from 'vant/lib/cascader'
import 'vant/lib/cascader/style'
import VanPicker from 'vant/lib/picker'
import 'vant/lib/picker/style'
import VanDatetimePicker from 'vant/lib/datetime-picker'
import 'vant/lib/datetime-picker/style'
import VanToast from 'vant/lib/toast'
import 'vant/lib/toast/style'

import moment from 'moment'
import { processTypeList, rdcTypeList } from '../utils/common'
const rdcType2label = rdcTypeList.reduce((o, i) => !void (o[i.value] = i.label) && o, {})
const processType2label = processTypeList.reduce((o, i) => !void (o[i.value] = i.label) && o, {})

export default {
  components: { VanNavBar, VanPopup, VanCascader, VanPicker, VanDatetimePicker },
  props: {
    deptTree: { type: Array, default: () => [] },
    deptMap: { type: Object, default: () => ({}) },
    value: {
      type: Object,
      default: () => ({
        rdcType: '',
        deptId: '',
        processType: '',
        monthFrom: '',
        monthTo: ''
      })
    }
  },
  data() {
    return {
      rdcTypeList,
      processTypeList,
      showCloseBtn: false,
      deptPicker: false,
      pickDeptId: '',
      processPicker: false,
      rdcPicker: false,

      monthFromPicker: false,
      monthToPicker: false,
      maxDate: moment().endOf('month').toDate(),
      currMonthFrom: new Date(),
      currMonthTo: new Date()
    }
  },
  computed: {
    queryParams: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    showDeptName() {
      const { deptId } = this.queryParams
      if (!deptId) return ''
      const item = this.deptMap[deptId]
      return item?.label || ''
    },
    showProcessName() {
      return processType2label[this.queryParams.processType]
    },
    showrRdcName() {
      return rdcType2label[this.queryParams.rdcType]
    },
    showMonthFrom() {
      const yearMonth = this.queryParams.monthFrom || ''
      if (!yearMonth) return ''
      return yearMonth.replace('-', '.')
    },
    showMonthTo() {
      const yearMonth = this.queryParams.monthTo || ''
      if (!yearMonth) return ''
      return yearMonth.replace('-', '.')
    }
  },
  mounted() {
    // 用于 app 端关闭 InAppBrowser。暂不启用
    // this.showCloseBtn = !!window?.webkit?.messageHandlers?.cordova_iab
  },
  methods: {
    onClickRight() {
      if (!this.showCloseBtn) return
      window.webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify({ action: 'close' }))
    },
    openDeptPicker() {
      this.pickDeptId = this.queryParams.deptId
      this.deptPicker = true
    },
    changeDeptId(deptId) {
      this.queryParams = { ...this.queryParams, deptId }
      this.$emit('change', { key: 'deptId', deptId })
      this.deptPicker = false
    },
    onDeptConfirm() {
      const deptId = this.pickDeptId
      if (!deptId) return (this.deptPicker = false)
      this.changeDeptId(deptId)
    },
    onDeptFinish({ value }) {
      this.changeDeptId(value)
    },
    onProcessPicker(item) {
      this.queryParams = { ...this.queryParams, processType: item.value }
      this.$emit('change', { key: 'processType', processType: item.value })
      this.processPicker = false
    },
    onRdcPicker(item) {
      this.queryParams = { ...this.queryParams, rdcType: item.value }
      this.$emit('change', { key: 'rdcType', rdcType: item.value })
      this.rdcPicker = false
    },
    monthFmt(type, val) {
      if (type === 'year') return `${val}年`
      if (type === 'month') return `${val}月`
      return val
    },
    openMonthPicker(action) {
      const isFrom = action === 'from'
      const yearMonth = isFrom ? this.queryParams.monthFrom : this.queryParams.monthTo
      const date = moment(`${yearMonth}-01`).toDate()
      if (isFrom) {
        this.currMonthFrom = date
        this.monthFromPicker = true
        return
      }
      this.currMonthTo = date
      this.monthToPicker = true
    },
    onMonthFromPicker(val) {
      const { monthTo } = this.queryParams
      const from = moment(val)
      const to = moment(`${monthTo}-01`)
      if (from.isAfter(to)) return VanToast(`不能大于结束月份 \n ${monthTo}`)
      if (to.diff(from, 'years') >= 1) return VanToast('间隔应小于一年')

      const monthFrom = from.format('YYYY-MM')
      this.queryParams = { ...this.queryParams, monthFrom }
      this.$emit('change', { key: 'monthRange', monthFrom, monthTo })
      this.monthFromPicker = false
    },
    onMonthToPicker(val) {
      const { monthFrom } = this.queryParams
      const from = moment(`${monthFrom}-01`)
      const to = moment(val)
      if (to.isBefore(from)) return VanToast(`不能小于起始月份 \n ${monthFrom}`)
      if (to.diff(from, 'years') >= 1) return VanToast('间隔应小于一年')

      const monthTo = to.format('YYYY-MM')
      this.queryParams = { ...this.queryParams, monthTo }
      this.$emit('change', { key: 'monthRange', monthFrom, monthTo })
      this.monthToPicker = false
    }
  }
}
</script>
<style lang="scss" scoped>
.top-select-mobile {
  position: sticky;
  z-index: 9;
  text-align: center;
  color: #333;
  border-bottom: 1px solid #f2f2f2;
}
.select-box {
  background-color: white;
  padding: 15px 10px;
  margin-top: 5px;
}
.label-box {
  display: flex;
  justify-content: center;
  align-items: center;
  .label {
    font-size: 14px;
    font-weight: bold;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 5px;
  }
}
.dept-tree-title {
  width: calc(100vw - 32px);
  display: flex;
  justify-content: space-between;
}
</style>
